/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SLE_TYPE_TRANS_UTILS_H
#define SLE_TYPE_TRANS_UTILS_H
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/**
 * @brief swift sle mac addr from uint8_t addrU8[SLE_DEVICE_ADDRESS_LEN] to char* addrStr
 *
 * @param uint8_t[SLE_DEVICE_ADDRESS_LEN] addrU8
 * @return char* macStr
 * @exemple:
 * uint8_t addrU8[SLE_DEVICE_ADDRESS_LEN] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
 * printf("sle mac addr: " MACSTR "\n", MAC2STR(addrU8));
 * char addrStr[SLE_DEVICE_ADDRESS_LEN*3];  //每个字节转换为两个字符，冒号占用一个字符，加上结束符 "\0"
 * sprintf(addrStr, MACSTR, MAC2STR(addrU8）);
 * printf("sle mac addr: %s\n", addrStr);
 */
#ifndef MAC2STR
#define MAC2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5]
#endif

#ifndef MACSTR
#define MACSTR "%02X:%02X:%02X:%02X:%02X:%02X"
#endif

#ifndef MAC2STRPRI
#define MAC2STRPRI(a) (a)[0], (a)[4], (a)[5]
#endif

#ifndef MACSTRPRI
#define MACSTRPRI "%{public}02X:**:**:**:%{public}02X:%{public}02X"
#endif

/**
 * @brief swift char to uint8_t
 *
 * @param char c
 * @return uint8_t
 */
#ifndef Hex2Num
#define Hex2Num(c)                              \
    (c >= '0' && c <= '9') ?  (c - '0') :       \
    ((c >= 'a' && c <= 'f') ?  (c - 'a' + 10) : \
    ((c >= 'A' && c <= 'F') ?  (c - 'A' + 10) : \
    0xff))
#endif

/**
 * @brief swift sle mac addr from char* macStr to uint8_t addrU8[SLE_DEVICE_ADDRESS_LEN]
 *
 * @param [out] uint8_t[SLE_DEVICE_ADDRESS_LEN] addrU8
 * @param [in] char* macStr
 * @exemple:
 *  char* macStr = "00:01:02:03:04:05";
 *  uint8_t addrU8[SLE_DEVICE_ADDRESS_LEN];
 *  Str2Mac(addrU8, macStr);
 */
#ifndef Str2Mac
#define Str2Mac(addrU8, macStr) \
    do { \
        uint8_t _macAddr[SLE_DEVICE_ADDRESS_LEN]; \
        size_t _index = 0; \
        const char* _ptr = macStr; \
        while (_index < SLE_DEVICE_ADDRESS_LEN) { \
            _macAddr[_index] = (uint8_t)strtoul(_ptr, NULL, 16); \
            _ptr = strchr(_ptr, ':') + 1; \
            _index++; \
        } \
        memcpy(addrU8, _macAddr, SLE_DEVICE_ADDRESS_LEN * sizeof(uint8_t)); \
    } while (0)
#endif


#endif //SLE_TYPE_TRANS_UTILS_H